package xiaopiya.robot.xmpp;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import xiaopiya.robot.IMessageSender;

/**
 * @author Ray (ayufox@gmail.com)
 * 
 */
public class XmppMessageSender implements IMessageSender
{
	private final static Log LOG = LogFactory.getLog(XmppMessageSender.class);

	private XMPPConnection xmppConnection;

	public void setXmppConnection(XMPPConnection xmppConnection)
	{
		this.xmppConnection = xmppConnection;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see xiaopiya.robot.IMessageSender#send(java.lang.String,
	 *      java.lang.String)
	 */
	public void send(String to, String message)
	{
		ChatManager chatManager = this.xmppConnection.getChatManager();

		Chat chat = chatManager.createChat(to, null);
		if (chat != null)
		{
			try
			{
				chat.sendMessage(message);
			} catch (XMPPException e)
			{
				LOG.error("error when send message[" + message + "] to [" + to
						+ "]", e);
			}
		}
		else
		{
			if (LOG.isInfoEnabled())
			{
				LOG.info("error when send message[" + message + "] to [" + to
						+ "]:empty chat");
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see xiaopiya.robot.IMessageSender#sendOnline(java.lang.String,
	 *      java.lang.String)
	 */
	public boolean sendOnline(String to, String message)
	{
		Roster roster = this.xmppConnection.getRoster();
		Presence pre = roster.getPresence(to);
		if (pre != null && pre.isAvailable())
		{
			send(to, message);
			return true;
		} else
		{
			return false;
		}
	}
}
